#!/bin/bash

# Build script for image2pcd project
# This script will configure and build the CMake project

set -e # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Project root directory (parent of scripts directory)
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_DIR="$PROJECT_DIR/build"

echo -e "${BLUE}=== Building image2pcd project ===${NC}"

# Create build directory if it doesn't exist
if [ ! -d "$BUILD_DIR" ]; then
    echo -e "${YELLOW}Creating build directory...${NC}"
    mkdir -p "$BUILD_DIR"
fi

# Change to build directory
cd "$BUILD_DIR"

# Check if CMake is available
if ! command -v cmake &>/dev/null; then
    echo -e "${RED}Error: CMake is not installed or not in PATH${NC}"
    exit 1
fi

echo -e "${YELLOW}Configuring CMake...${NC}"

# Configure CMake
cmake -DCMAKE_BUILD_TYPE=Release "$PROJECT_DIR"

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: CMake configuration failed${NC}"
    exit 1
fi

echo -e "${YELLOW}Building project...${NC}"

# Build the project
make -j$(nproc)

if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Build failed${NC}"
    exit 1
fi

echo -e "${GREEN}Build completed successfully!${NC}"
echo -e "${GREEN}Executable created: $PROJECT_DIR/image2pcd${NC}"

# Check if executable was created
if [ -f "$PROJECT_DIR/image2pcd" ]; then
    echo -e "${GREEN}✓ Executable found and ready to run${NC}"
else
    echo -e "${RED}✗ Executable not found${NC}"
    exit 1
fi

echo -e "${BLUE}=== Build Complete ===${NC}"
